from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .ser import *
from utils.tooljwt import myjwt
from datetime import datetime
from django.db import transaction


# Create your views here.


class LoginView(APIView):
    def post(self, request):
        name = request.data.get('name')
        password = request.data.get('password')
        user = AdminUser.objects.get(name=name)
        if not user:
            return Response({'code': 400, 'msg': '用户不存在'})
        if user.password == password:
            token = myjwt.jwt_encode({'id': user.id, 'name': user.name})
            print('token', token)
            return Response({'code': 200, 'msg': '登录成功', 'token': token,
                             'data': {'id': user.id, 'name': user.name, 'role': user.role.role_name}})
        else:
            return Response({'code': 400, 'msg': '密码错误'})


class RoleView(APIView):

    def get(self, request):
        role = Roles.objects.all()
        ser = RolesSer(role, many=True)
        return Response(ser.data)

    def post(self, request):
        name = request.data.get('name')
        role = Roles.objects.filter(role_name=name)
        if role:
            return Response({'code': 400, 'msg': '角色已存在'})
        else:
            role = Roles.objects.create(role_name=name)
            return Response({'code': 200, 'msg': '添加成功', 'data': {'role_name': role.role_name}})


class ResourceView(APIView):
    def get(self, request):
        # 获取查询参数 id
        id = request.query_params.get('id')

        if id:
            # 如果传递了 id，获取对应的二级分类
            try:
                second_level_resources = Resources.objects.filter(pid_id=id)
                if not second_level_resources.exists():
                    return Response(
                        {'error': 'No resources found for the given first_level_id'},
                        status=status.HTTP_404_NOT_FOUND
                    )
                second_level_ser = ResourcesSer(second_level_resources, many=True)
                return Response(second_level_ser.data)
            except Exception as e:
                return Response(
                    {'error': str(e)},
                    status=status.HTTP_400_BAD_REQUEST
                )
        else:
            # 如果没有传递 id，获取所有一级分类
            first_level_resources = Resources.objects.filter(pid__isnull=True)
            first_level_ser = ResourcesSer(first_level_resources, many=True)
            return Response(first_level_ser.data)

    def post(self, request):
        name = request.data.get('name')
        url = request.data.get('url')
        pid = request.data.get('pid')
        res = Resources.objects.filter(resource_name=name)
        if res:
            return Response({'code': 400, 'msg': '资源已存在'})
        else:
            resource = Resources.objects.create(resource_name=name, url=url, pid_id=pid)
            return Response({'code': 200, 'msg': '添加成功', 'data': {'name': resource.resource_name,
                                                                        'url': resource.url,
                                                                        'pid': resource.pid_id}})


class RoleResourceView(APIView):
    def get(self, request):
        role_resource = RoleResource.objects.all()
        ser = RoleResourceSer(role_resource, many=True)
        return Response(ser.data)


class AdminUserView(APIView):
    def get(self, request):
        admin_user = AdminUser.objects.all()
        ser = AdminUserSer(admin_user, many=True)
        return Response(ser.data)

    def post(self, request):
        name = request.data.get('name')
        password = request.data.get('password')
        role_id = request.data.get('role_id')
        use = AdminUser.objects.filter(name=name)
        if use:
            return Response({'code': 400, 'msg': '用户已存在'})
        else:
            admin_user = AdminUser.objects.create(name=name, password=password, role_id=role_id)
            return Response({'code': 200, 'msg': '添加成功', 'data': {'name': admin_user.name}})


class WorkflowView(APIView):
    def get(self, request):
        workflow = Workflow.objects.all()
        ser = WorkflowSer(workflow, many=True)
        return Response(ser.data)

    def post(self, request):
        name = request.data.get('name')
        params = request.data.get('params')
        status = request.data.get('status')
        work = Workflow.objects.filter(name=name)
        if work:
            return Response({'code': 400, 'msg': '流程已存在'})
        else:
            workser = WorkflowSer(data=request.data)
            if workser.is_valid():
                workser.save()
                return Response({'code': 200, 'msg': '添加成功', 'data': workser.data})
            else:
                return Response({'code': 400, 'msg': '添加失败', 'data': workser.errors})


class PositionView(APIView):
    def get(self, request):
        pos = Position.objects.all()
        ser = PositionSer(pos, many=True)
        return Response(ser.data)


class TaskView(APIView):
    def get(self, request):
        task = Task.objects.all()
        ser = TaskSer(task, many=True)
        return Response(ser.data)

    def post(self, request):
        name = request.data.get('name')
        params = request.data.get('params')
        workflow = request.data.get('workflow')
        user = request.data.get('user')
        next_audit = request.data.get('next_audit')
        task_status = request.data.get('task_status')

        task = Task.objects.filter(name=name)
        if task:
            return Response({'code': 400, 'msg': '任务已存在'})
        else:
            taskser = TaskSer(data=request.data)
            if taskser.is_valid():
                taskser.save()
                return Response({'code': 200, 'msg': '添加成功', 'data': taskser.data})
            else:
                return Response({'code': 400, 'msg': '添加失败', 'data': taskser.errors})

#
# class AuditRecordView(APIView):
#     def post(self, request):
#         task = request.data.get('task')
#         audit_user = request.data.get('audit_user')
#         audit_status = request.data.get('audit_status')
#         print(task, audit_user, audit_status)
#         record = Task.objects.get(id=task)
#         print(record)
#         if record:
#             recordser = AuditRecordSer(data=request.data)
#             if recordser.is_valid():
#                 recordser.save()
#
#                 if audit_status == 1:
#                     record.task_status = 2
#                     return Response({'code': 200, 'msg': '审核成功', 'data': recordser.data})
#                 else:
#                     return Response({'code': 400, 'msg': '审核失败'})
#         return Response({'code': 400, 'msg': '任务不存在'})


class AuditRecordView(APIView):
    def post(self, request):
        # 从请求数据中获取 task_id、audit_user 和 audit_status
        task_id = request.data.get('task')
        audit_user_id = request.data.get('audit_user')
        audit_status = request.data.get('audit_status')
        print(task_id, audit_user_id, audit_status)

        # 验证必填字段是否存在
        if not all([task_id, audit_user_id, audit_status]):
            return Response({
                'code': 400,
                'msg': '任务ID、审核用户和审核状态是必填项'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 验证 task_id 是否为有效的整数
        try:
            task_id = int(task_id)
        except ValueError:
            return Response({
                'code': 400,
                'msg': '任务ID必须为整数'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 尝试从数据库中获取对应的任务
        try:
            task = Task.objects.get(id=task_id)
            print(task)
        except Task.DoesNotExist:
            return Response({
                'code': 404,
                'msg': '任务不存在'
            }, status=status.HTTP_404_NOT_FOUND)

        # 准备审核记录的数据
        audit_data = {
            'task': task.id,
            'audit_user': audit_user_id,
            'audit_status': audit_status
        }
        print(audit_data)

        # 对审核记录数据进行序列化和验证
        serializer = AuditRecordSer(data=audit_data)
        if serializer.is_valid():
            with transaction.atomic():
                # 保存审核记录
                audit_record = serializer.save()
                print(audit_record)
                # 如果审核状态为通过，更新任务状态
                if audit_status == '1':
                    task.task_status = 3
                    task.save()

            return Response({
                'code': 201,
                'msg': '审核记录创建成功',
                'data': serializer.data
            }, status=status.HTTP_201_CREATED)

        return Response({
            'code': 400,
            'msg': '数据验证失败',
            'data': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)


